package it.nola.soccer;

import it.nola.soccer.adapter.TeamACAdapter;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * Questa classe controlla l'attività di editing/creazione della cronaca
 * 
 * @author paolo
 */
public class NoteEdit extends Activity {

    private EditText titleText;
    private EditText notesText;
    private EditText dateText;
    private AutoCompleteTextView team1Text;
    private AutoCompleteTextView team2Text;
    private EditText assistentsText;
    private EditText corner1;
    private EditText corner2;
    private EditText foul1;
    private EditText foul2;
    private EditText refereeText;
    private EditText resultText;
    private EditText placeText;
    private Spinner playerNrSpinner;
    private Long rowId;
    private DbHelper dbHelper;
    private long default_nr_players;

    public void addCorner1(View view) {
	addOne(corner1);
    }

    public void addCorner2(View view) {
	addOne(corner2);
    }

    /**
     * Aggiungi un falloalla squadra di casa
     * 
     * @param view
     */
    public void addFoul1(View view) {
	addOne(foul1);
    }

    /**
     * Aggiungi un fallo alla squadra in trasferta
     * 
     * @param view
     */
    public void addFoul2(View view) {
	addOne(foul2);
    }

    private void addOne(EditText et) {
	String txt=et.getText().toString();
	if ("".equals(txt)) {
	    et.setText("1");
	}
	else {
	    try {
		et.setText(Integer.toString(Integer.parseInt(txt)+1));
	    }
	    catch (NumberFormatException e) {
		et.setText("1");
	    }
	}

    }

    public void chiudi(View view) {
	setResult(RESULT_OK);
	finish();
    }

    private boolean controllaGiocatori() {
	if (!dbHelper.areThereAllPlayer(rowId)) {
	    Toast toast=Toast.makeText(this, getString(R.string.player_missing_error), Toast.LENGTH_SHORT);
	    toast.show();
	    return false;
	}
	return true;
    }

    public void editAction(View view) {
	if (!isSaved()||!isTeam1Set()||!isTeam2Set()) {
	    return;
	}
	Intent i=new Intent(this, ActionEdit.class);
	i.putExtra(Const.Players.KEY_CRONACA, rowId);
	i.putExtra(Const.HOME_TEAM.toString(), team1Text.getText());
	i.putExtra(Const.FOREIGN_TEAM.toString(), team2Text.getText());
	startActivityForResult(i, SoccerNotes.ACTION_EDIT);
    }

    public void editCard(View view) {
	if (!controllaGiocatori()) {
	    return;
	}
	Intent i=new Intent(this, CardEdit.class);
	i.putExtra(Const.Players.KEY_CRONACA, rowId);
	i.putExtra(Const.HOME_TEAM.toString(), team1Text.getText());
	i.putExtra(Const.FOREIGN_TEAM.toString(), team2Text.getText());
	startActivityForResult(i, SoccerNotes.CARD_EDIT);
    }

    public void editGoal(View view) {
	if (!controllaGiocatori()) {
	    return;
	}
	Intent i=new Intent(this, GoalEdit.class);
	i.putExtra(Const.Players.KEY_CRONACA, rowId);
	i.putExtra(Const.HOME_TEAM.toString(), team1Text.getText());
	i.putExtra(Const.FOREIGN_TEAM.toString(), team2Text.getText());
	startActivityForResult(i, SoccerNotes.GOAL_EDIT);
    }

    public void editSubst(View view) {
	if (!controllaGiocatori()) {
	    return;
	}
	Intent i=new Intent(this, SubstEdit.class);
	i.putExtra(Const.Players.KEY_CRONACA, rowId);
	i.putExtra(Const.HOME_TEAM.toString(), team1Text.getText());
	i.putExtra(Const.FOREIGN_TEAM.toString(), team2Text.getText());
	startActivityForResult(i, SoccerNotes.SUBST_EDIT);
    }

    /**
     * Apre la finestra di gestione della squadra di casa
     * 
     * @param view
     */
    public void editTeam1(View view) {
	if (!isSaved()||!isTeam1Set()) {
	    return;
	}
	Intent i=new Intent(this, TeamEdit.class);
	i.putExtra(Const.Players.KEY_CRONACA, rowId);
	i.putExtra(Const.Players.KEY_TEAM, Const.HOME_TEAM);
	i.putExtra(Const.Players.NAME, team1Text.getText().toString());
	i.putExtra(Const.Config.KEY_DEFAULT_PL_NUMBER, getNrPlayers());
	startActivityForResult(i, SoccerNotes.TEAM_EDIT);
    }

    /**
     * Apre la finestra di gestione della squadra in trasferta
     * 
     * @param view
     */
    public void editTeam2(View view) {
	if (!isSaved()||!isTeam2Set()) {
	    return;
	}
	Intent i=new Intent(this, TeamEdit.class);
	i.putExtra(Const.Players.KEY_CRONACA, rowId);
	i.putExtra(Const.Players.KEY_TEAM, Const.FOREIGN_TEAM);
	i.putExtra(Const.Players.NAME, team2Text.getText().toString());
	i.putExtra(Const.Config.KEY_DEFAULT_PL_NUMBER, getNrPlayers());
	startActivityForResult(i, SoccerNotes.TEAM_EDIT);
    }

    public int getNrPlayers() {
	Resources res=getResources();
	return Integer.parseInt(res.getStringArray(R.array.player_numbers)[playerNrSpinner.getSelectedItemPosition()]);
    }

    /**
     * @return restituisce l'identificativo della cronaca su cui sto lavorando
     */
    public Long getRowId() {
	return rowId;
    }

    private boolean isSaved() {
	if (rowId==null) {
	    Toast t=Toast.makeText(this, getString(R.string.note_not_saved_error), Toast.LENGTH_SHORT);
	    t.show();
	    return false;
	}
	return true;
    }

    private boolean isTeam1Set() {
	if ("".equals(team1Text.getText().toString().trim())) {
	    Toast toast=Toast.makeText(this, getString(R.string.team1_missing_error), Toast.LENGTH_SHORT);
	    toast.show();
	    return false;
	}
	return true;
    }

    private boolean isTeam2Set() {
	if ("".equals(team2Text.getText().toString().trim())) {
	    Toast toast=Toast.makeText(this, getString(R.string.team2_missing_error), Toast.LENGTH_SHORT);
	    toast.show();
	    return false;
	}
	return true;
    }

    /**
     * Azioni da effettuare alla creazione dell'atività
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setTitle(getString(R.string.match));
	dbHelper=new DbHelper(this);
	dbHelper.open();
	setContentView(R.layout.note_edit);
	Bundle extras=getIntent().getExtras();
	rowId=savedInstanceState!=null ? savedInstanceState.getLong(Const.Cronache.KEY_ROWID) : null;
	if (rowId==null) {
	    rowId=extras.getLong(Const.Cronache.KEY_ROWID)==0 ? null : extras.getLong(Const.Cronache.KEY_ROWID);
	}
	default_nr_players=extras.getInt(Const.Config.KEY_DEFAULT_PL_NUMBER);
	prepareFields();
	populateFields();
    }

    /**
     * Quando l'attività va in pausa bisogna salvare
     */
    @Override
    protected void onPause() {
	super.onPause();
	saveState();
    }

    /**
     * al resume recupera i campi
     */
    @Override
    protected void onResume() {
	super.onResume();
	populateFields();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
	super.onSaveInstanceState(outState);
	if (rowId!=null) {
	    outState.putLong(Const.Cronache.KEY_ROWID, rowId);
	}
    }

    @Override
    protected void onStop() {
	super.onPause();
	saveState();
    }

    private void populateFields() {
	if (rowId==null) {
	    long id=dbHelper.createNote(getString(R.string.default_title), getString(R.string.default_notes), "0-0",
		getString(R.string.stadium), default_nr_players, 0, 0, 0, 0);
	    if (id>0) {
		rowId=id;
	    }
	}
	if (rowId!=null) { // recupero dal db
	    Cursor cc=dbHelper.recuperaCronaca(rowId);
	    startManagingCursor(cc);
	    cc.moveToFirst();
	    titleText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_TITLE)));
	    notesText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_BODY)));
	    dateText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_MATCH_DATE)));
	    team1Text.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_TEAM1)));
	    team2Text.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_TEAM2)));
	    assistentsText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_ASSISTENTS)));
	    refereeText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_REFEREE)));
	    resultText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_RESULT)));
	    corner1.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_CORNER1)));
	    corner2.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_CORNER2)));
	    foul1.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_FOUL1)));
	    foul2.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_FOUL2)));
	    placeText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_PLACE)));
	    playerNrSpinner.setSelection(cc.getInt(cc.getColumnIndex(Const.Cronache.KEY_PLAYER_NR)));
	    playerNrSpinner.setEnabled("".equals(team1Text.getText().toString())
		&&"".equals(team2Text.getText().toString())&&!dbHelper.areThereAnyPlayer(rowId, Const.HOME_TEAM)
		&&!dbHelper.areThereAnyPlayer(rowId, Const.FOREIGN_TEAM));
	}
    }

    /**
     * Inizializza i campi presenti nella View
     */
    private void prepareFields() {
	titleText=(EditText) findViewById(R.id.title);
	notesText=(EditText) findViewById(R.id.body);
	dateText=(EditText) findViewById(R.id.match_date);
	assistentsText=(EditText) findViewById(R.id.assistents);
	refereeText=(EditText) findViewById(R.id.referee);
	resultText=(EditText) findViewById(R.id.result);
	placeText=(EditText) findViewById(R.id.place);
	corner1=(EditText) findViewById(R.id.corner1);
	corner2=(EditText) findViewById(R.id.corner2);
	foul1=(EditText) findViewById(R.id.foul1);
	foul2=(EditText) findViewById(R.id.foul2);
	TeamACAdapter adapter=new TeamACAdapter(this, android.R.layout.simple_spinner_dropdown_item, dbHelper);
	team1Text=(AutoCompleteTextView) findViewById(R.id.team1);
	team2Text=(AutoCompleteTextView) findViewById(R.id.team2);
	team1Text.setAdapter(adapter);
	team2Text.setAdapter(adapter);
	playerNrSpinner=(Spinner) findViewById(R.id.nr_players);
	ArrayAdapter<CharSequence> plNrAdapter=ArrayAdapter.createFromResource(this, R.array.player_numbers,
	    android.R.layout.simple_spinner_dropdown_item);
	playerNrSpinner.setAdapter(plNrAdapter);
    }

    public void salva(View view) {
	saveState();
	Toast toast=Toast.makeText(this, getString(R.string.just_saved), Toast.LENGTH_LONG);
	toast.show();
    }

    private void saveState() {
	String title=titleText.getText().toString();
	String notes=notesText.getText().toString();
	String date=dateText.getText().toString();
	String team1=team1Text.getText().toString();
	String team2=team2Text.getText().toString();
	String assistents=assistentsText.getText().toString();
	String referee=refereeText.getText().toString();
	String result=resultText.getText().toString();
	String place=placeText.getText().toString();
	Long nrPlayers=playerNrSpinner.getSelectedItemId();
	int c1=Integer.parseInt(corner1.getText().toString());
	int c2=Integer.parseInt(corner2.getText().toString());
	int f1=Integer.parseInt(foul1.getText().toString());
	int f2=Integer.parseInt(foul2.getText().toString());
	dbHelper.updateNote(rowId, title, notes, date, team1, team2, assistents, referee, result, place, nrPlayers, c1,
	    c2, f1, f2);
    }

    public void subCorner1(View view) {
	subOne(corner1);
    }

    public void subCorner2(View view) {
	subOne(corner2);
    }

    public void subFoul1(View view) {
	subOne(foul1);
    }

    public void subFoul2(View view) {
	subOne(foul2);
    }

    private void subOne(EditText et) {
	String txt=et.getText().toString();
	if ("".equals(txt)||"0".equals(txt)) {
	    et.setText("0");
	}
	else {
	    try {
		et.setText(Integer.toString(Integer.parseInt(txt)-1));
	    }
	    catch (NumberFormatException e) {
		et.setText("0");
	    }
	}
    }

}
